<?php


namespace app\logic\job;
use app\api\model\merchant\MerchantModel;
use app\api\model\merchant\MerchantOrderBill;
use think\facade\Log;
use think\queue\Job;
use ulit\thirdPayment\CanLangPay;
use ulit\thirdPayment\SafePay;
use app\api\model\order\Order;
class CanLangJob
{

    /**
     * fire方法是消息队列默认调用的方法
     * @param Job $job 当前的任务对象
     * @param array|mixed $data 发布任务时自定义的数据
     */

    // 定义任务的最大重试次数
    public function maxAttempts()
    {
        return 5; // 最大重试5次
    }


    public function fire(Job $job, $data)
    {

        if (empty($data)) {
            Log::write(sprintf('[%s][%s] 队列无消息', __CLASS__, __FUNCTION__));
            return false;
        }
        //获取队列提交信息
        $order_sn = $data['order_sn'];
        //如果有并发通知过来只处理一个
        $redislock = redisLocker();
        Log::record('队列参数'.json_encode($data), 'Pay');
        $resource = $redislock->lock('pay.' . $order_sn, 8000);   //单位毫秒
        Log::write(json_encode($resource),'pay');
        echo 'resource=>',json_encode($resource);
        //说明有订单在处理
        if (!$resource) {
            return $job->delete();
        }
        $delay = 3; // 延迟时间，单位秒


        $orderInfo = Order::where(['order_sn' => $order_sn])->field(['merchant_id', 'amount', 'commission','status','order_sn','third_ext_json','notify_state'])->find();

        $result =$this->payOrder($order_sn);
        if(!$orderInfo){
             $job->delete();
             Log::write('订单信息不存在');
            return false;
        }

        $this->updateOrderStatus($orderInfo, $result);
        if ($result['status'] == 'DEALING') {
            Log::info('订单支付中，任务将被重新推送');

            $job->release($delay);
            $redislock->unlock(['resource' => 'pay.' . $order_sn, 'token' => $resource['token']]);
            return true;
        }else{
            //通知区域
            $notify = new  Notify();
            $notify_state=$orderInfo['notify_state'] ?:0;
            if($notify_state!=1){
                $state= $notify->run($orderInfo['third_ext_json'],$orderInfo['merchant_id'],$result);
                if($state){
                    Order::where(['order_sn' => $order_sn])->update(['notify_state'=>1]);
                }
            }

        }

        $redislock->unlock(['resource' => 'pay.' . $order_sn, 'token' => $resource['token']]);
        return $job->delete();

    }


    public function payOrder($order_sn)
    {
        try {

            $result=CanLangPay::getInstance()->query($order_sn);

            Log::record('pay_callback'.json_encode($result));

            if (isset($result['data'])) {
                Log::info('支付回调结果'.json_encode($result));
                return $result['data'];
            }

            Log::error('支付回调结果无效');
            return ['status' => -1, 'message' => '支付回调结果无效'];
//            $arr=[];
//            // 定义数组
//            $numbers = [0, 1, 2, 4];
//
//// 使用 array_rand() 从数组中随机取出一个键
//            $randomKey = array_rand($numbers);
//
//            Log::write($randomKey);
//// 使用随机键从数组中获取对应的值
//            $randomValue = $numbers[$randomKey];
//            $arr['result']['orderStatus']=$randomValue;
//            $arr['result']['message']='test';
            // return $arr['result'];

            //

        } catch (\Exception $e) {
            $error_info = $e->getMessage();

            Log::record('pay_callback_error'.json_encode($error_info));

            return ['orderStatus' => -1, 'message' => $e->getMessage()];
        }
    }

    /**
     * 更新订单状态
     *
     * @param string $order_sn 订单号
     * @param array $result 支付结果
     */
    private function updateOrderStatus($orderInfo, $result)
    {

        if ($orderInfo) {
            $log['order_sn']=$orderInfo['order_sn'];
            $log['merchant_id']=$orderInfo['merchant_id'];
            $log['money']=$orderInfo['commission'];
            $true=MerchantOrderBill::createLog($log);
            if ($result['status'] == 1 && $true) {

                MerchantModel::where(['id' => $orderInfo['merchant_id']])
                    ->dec('money', $orderInfo['commission'])->update();
            }
            $status = match ($result['status']) {
                'SUCCESS' => 1,
                'REFUND' => 6,
                'DEALING' => 2,
                default => 4,
            };
            $update['status']=$status;
            $update['pay_ext_json']=$result;
            !empty($result['remark']) &&  $update['pay_error_json']=['msg'=>$result['remark']];
            Order::where(['order_sn' => $orderInfo['order_sn']])->update($update);
        }
    }

    public function doJob($data)
    {
        echo '执行时间--->'.date('Y-m-d H:i:s')."\n";
        return false;
    }

    public function failed($data){

        // ...任务达到最大重试次数后，失败了
        Log::error('支付任务失败'.json_encode(['data' => $data], JSON_UNESCAPED_UNICODE));
    }


}
